package com.itjin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.mapper.UserMapper;
import com.itjin.model.domain.entity.User;
import com.itjin.service.MangerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import static com.itjin.contant.UserConstant.DEFAULT_ROLE;
import static com.itjin.contant.UserConstant.SALT;
import com.itjin.model.domain.dto.AddUserDTO;
import com.itjin.model.domain.dto.EditUserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class MangerServiceImpl extends ServiceImpl<UserMapper, User> implements MangerService {

  private static final String DEFAULT_PASSWORD = "Swust123";
  private static final Logger log = LoggerFactory.getLogger(MangerServiceImpl.class);

  @Override
  public Page<User> listUsersByPage(int current, int size, String keyword) {
    // 创建查询条件
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("isDelete", 0);

    // 如果有关键词，添加模糊查询条件
    if (StringUtils.isNotBlank(keyword)) {
      wrapper.and(w -> w.like("userAccount", keyword)
          .or()
          .like("phone", keyword));
    }

    // 按创建时间降序排序
    wrapper.orderByDesc("createTime");

    return baseMapper.selectPage(new Page<>(current, size), wrapper);
  }

  @Override
  public boolean addUser(AddUserDTO addUserDTO) {
    // 1. 校验必填参数
    if (addUserDTO == null || StringUtils.isAnyBlank(
        addUserDTO.getUserAccount(),
        addUserDTO.getUserPassword(),
        addUserDTO.getPhone())) {
      throw new RuntimeException("必填参数不能为空");
    }

    // 2. 账户不能重复
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("userAccount", addUserDTO.getUserAccount());
    long count = this.count(queryWrapper);
    if (count > 0) {
      throw new RuntimeException("账号已存在");
    }

    // 3. 创建用户对象
    User user = new User();
    BeanUtils.copyProperties(addUserDTO, user);

    // 4. 密码加密
    String encryptPassword = DigestUtils.md5DigestAsHex(
        (SALT + addUserDTO.getUserPassword()).getBytes());
    user.setUserPassword(encryptPassword);

    // 5. 设置默认值
    if (user.getUserRole() == null) {
      user.setUserRole(DEFAULT_ROLE);
    }
    if (user.getUserStatus() == null) {
      user.setUserStatus(0);
    }

    // 6. 保存用户
    return this.save(user);
  }

  @Override
  public boolean editUser(EditUserDTO editUserDTO) {
    // 1. 参数校验
    if (editUserDTO == null || editUserDTO.getId() == null) {
      throw new RuntimeException("参数错误");
    }

    // 2. 检查用户是否存在
    User existUser = this.getById(editUserDTO.getId());
    if (existUser == null) {
      throw new RuntimeException("用户不存在");
    }

    // 添加日志
    log.debug("接收到的个人简介: {}", editUserDTO.getBiography());

    User user = new User();
    user.setId(editUserDTO.getId());
    user.setUsername(editUserDTO.getUsername());
    user.setAvatar(editUserDTO.getAvatar());
    user.setPhone(editUserDTO.getPhone());
    user.setEmail(editUserDTO.getEmail());
    user.setGender(editUserDTO.getGender());
    user.setBiography(editUserDTO.getBiography());

    // 添加日志
    log.debug("设置到User对象的个人简介: {}", user.getBiography());

    try {
      boolean result = this.updateById(user);
      // 添加日志
      log.debug("更新结果: {}", result);
      return result;
    } catch (Exception e) {
      log.error("更新用户信息失败", e);
      throw new RuntimeException("更新用户信息失败");
    }
  }

  @Override
  public boolean resetUserPassword(Integer userId) {
    // 1. 参数校验
    if (userId == null || userId <= 0) {
      throw new RuntimeException("用户ID不合法");
    }

    // 2. 检查用户是否存在
    User user = this.getById(userId);
    if (user == null) {
      throw new RuntimeException("用户不存在");
    }

    // 3. 加密默认密码
    String encryptPassword = DigestUtils.md5DigestAsHex((SALT + DEFAULT_PASSWORD).getBytes());

    // 4. 更新密码
    User updateUser = new User();
    updateUser.setId(userId);
    updateUser.setUserPassword(encryptPassword);

    return this.updateById(updateUser);
  }

  @Override
  public boolean changePassword(Integer userId, String currentPassword, String newPassword) {
    // 1. 参数校验
    if (userId == null || userId <= 0) {
      throw new RuntimeException("用户ID不合法");
    }
    if (StringUtils.isAnyBlank(currentPassword, newPassword)) {
      throw new RuntimeException("密码不能为空");
    }
    if (newPassword.length() < 8) {
      throw new RuntimeException("新密码长度不能小于8位");
    }

    // 2. 检查用户是否存在
    User user = this.getById(userId);
    if (user == null) {
      throw new RuntimeException("用户不存在");
    }

    // 3. 验证当前密码是否正确
    String encryptCurrentPassword = DigestUtils.md5DigestAsHex(
        (SALT + currentPassword).getBytes());
    if (!user.getUserPassword().equals(encryptCurrentPassword)) {
      throw new RuntimeException("当前密码错误");
    }

    // 4. 加密新密码
    String encryptNewPassword = DigestUtils.md5DigestAsHex(
        (SALT + newPassword).getBytes());

    // 5. 更新密码
    User updateUser = new User();
    updateUser.setId(userId);
    updateUser.setUserPassword(encryptNewPassword);

    return this.updateById(updateUser);
  }
}
